package com.example.pei.ithinklearnt.model;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.bean.Skill;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.bean.UserSkill;
import com.example.pei.ithinklearnt.utils.ToastUtil;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class SkillModelImp implements SkillModel {

    @Override
    public void achieveAllSkills(final achieveSkillsListener listener) {
        BmobQuery<Skill> query = new BmobQuery<Skill>();
        query.order("-createdAt");   //按时间降序
        query.findObjects(new FindListener<Skill>() {
            @Override
            public void done(List<Skill> object, BmobException e) {
                if(e==null){
                    String[] skills=new String[object.size()];
                    for(int i=0;i<object.size();i++){
                        skills[i]=object.get(i).getSkillName();
                    }
                    listener.succeed(skills);

                }else{
                    listener.failed();
                }
            }

        });
    }

    @Override
    public void allSkillsWriteToLocal(String[] skillls ) {
        final SharedPreferences.Editor editor= AppApplication.getContext().getSharedPreferences("_skills", Context.MODE_PRIVATE).edit();
        editor.putInt("total",skillls.length);   //更新技能的数量
        for(int i=0;i<skillls.length;i++){
            editor.putString("skill_"+i,skillls[i]);
        }
        editor.apply();
    }

    @Override
    public String[] readAllSkills() {
        SharedPreferences preferences=AppApplication.getContext().getSharedPreferences("_skills",Context.MODE_PRIVATE);
        int num=preferences.getInt("total",0);
        String[] skills=new String[num];
        for(int i=0;i<num;i++){
            skills[i]=preferences.getString("skill_"+i,"emmmmm");
        }
        return skills;
    }

    @Override
    public void achieveUserSkills(UserInfo user,final achieveUserSkillsListener listener) {
        BmobQuery<UserSkill> query = new BmobQuery<>();
        query.addWhereEqualTo("user", user);     //名字
        //判断是否有缓存，该方法必须放在查询条件（如果有的话）都设置完之后再来调用才有效，就像这里一样。
//        boolean isCache = query.hasCachedResult(UserSkill.class);
//        if(isCache){
//            query.setCachePolicy(BmobQuery.CachePolicy.CACHE_THEN_NETWORK);   // 如果有缓存的话，则设置策略为CACHE_ELSE_NETWORK
//        }else{
//            query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);   // 如果没有缓存的话，则设置策略为NETWORK_ELSE_CACHE
//        }
        query.findObjects(new FindListener<UserSkill>() {
            @Override
            public void done(List<UserSkill> object, BmobException e) {
                 if(e==null){
                    if(object.size()==1){
                        List<String> listStrongSkills=object.get(0).getStrongSkills();
                        List<String> listWeakSkills=object.get(0).getWeakSkills();

                        String[] weakSkills=new String[listWeakSkills.size()];
                        for(int i=0;i<listWeakSkills.size();i++){
                            weakSkills[i]=listWeakSkills.get(i);
                        }

                        if(listStrongSkills!=null&&listStrongSkills.size()!=0){
                            String[] strongSkills=new String[listStrongSkills.size()];
                            for(int i=0;i<listStrongSkills.size();i++){
                                strongSkills[i]=listStrongSkills.get(i);
                            }
                            listener.succeed(weakSkills,strongSkills);
                        }else{
                            listener.succeed(weakSkills,null);
                        }



                    }else{
                        listener.failed();
                    }
                }else{
                    listener.failed();
                }
            }
        });
    }

    @Override
    public void achieveAllUserSkills(final achieveAllUserSkillsListerner listener) {
        BmobQuery<UserSkill> query = new BmobQuery<>();
        //判断是否有缓存，该方法必须放在查询条件（如果有的话）都设置完之后再来调用才有效，就像这里一样。
//        boolean isCache = query.hasCachedResult(UserSkill.class);
//        if(isCache){
//            query.setCachePolicy(BmobQuery.CachePolicy.CACHE_THEN_NETWORK);   // 如果有缓存的话，则设置策略为CACHE_ELSE_NETWORK
//        }else{
//            query.setCachePolicy(BmobQuery.CachePolicy.NETWORK_ELSE_CACHE);   // 如果没有缓存的话，则设置策略为NETWORK_ELSE_CACHE
//        }
        query.include("user");// 希望在查询信息的同时也把发布人的信息查询出来
        query.findObjects(new FindListener<UserSkill>() {
            @Override
            public void done(List<UserSkill> object, BmobException e) {
                if(e==null){
                    if(object.size()>=0){
                        listener.succeed(object);
                    }else{
                        listener.failed();
                    }
                }else{
                    listener.failed();
                }
            }
        });
    }

    @Override
    public void writeUserWeakSkillsToLocal(String userID,String[] weakSkills ) {
        final SharedPreferences.Editor editor1= AppApplication.getContext().getSharedPreferences(userID+"_weak_skills", Context.MODE_PRIVATE).edit();
        editor1.putInt("total",weakSkills.length);   //更新技能的数量
        for(int i=0;i<weakSkills.length;i++){
            editor1.putString("skill_"+i,weakSkills[i]);
        }
        editor1.apply();

    }

    @Override
    public void writeUserStrongSkillsToLocal(String userID, String[] strongSkills) {

        final SharedPreferences.Editor editor2= AppApplication.getContext().getSharedPreferences(userID+"_strong_skills", Context.MODE_PRIVATE).edit();
        editor2.putInt("total",strongSkills.length);   //更新技能的数量
        for(int i=0;i<strongSkills.length;i++){
            editor2.putString("skill_"+i,strongSkills[i]);
        }
        editor2.apply();
    }


    @Override
    public String[] readStrongSkills(String userID) {
        SharedPreferences preferences=AppApplication.getContext().getSharedPreferences(userID+"_strong_skills",Context.MODE_PRIVATE);
        int num=preferences.getInt("total",0);
        String[] skills=new String[num];
        for(int i=0;i<num;i++){
            skills[i]=preferences.getString("skill_"+i,"emmmmm");
        }
        return skills;
    }

    @Override
    public String[] readWeakSkills(String userID) {
        SharedPreferences preferences=AppApplication.getContext().getSharedPreferences(userID+"_weak_skills",Context.MODE_PRIVATE);
        int num=preferences.getInt("total",0);
        String[] skills=new String[num];
        for(int i=0;i<num;i++){
            skills[i]=preferences.getString("skill_"+i,"emmmmm");
        }
        return skills;
    }

    @Override
    public void updateUserSkill(final UserInfo user, String[] weakSkills, String[] strongSkills, final updateUserSkillListener listener) {
        final List<String> listWeak;
        final List<String> listStrong;
        String userName=user.getUsername();
        if(weakSkills!=null) {
            listWeak = Arrays.asList(weakSkills);
        }else{
            listWeak=null;
        }
        if(strongSkills!=null){
            listStrong=Arrays.asList(strongSkills);
        }else{
            listStrong=null;
        }

        BmobQuery<UserSkill> query = new BmobQuery<>();
        query.addWhereEqualTo("user", user);  // 查询当前用户的技能
        query.findObjects(new FindListener<UserSkill>() {
            @Override
            public void done(List<UserSkill> object, BmobException e) {
                if(e==null){
                    if(object.size()==1){   //存在这条记录，则修改
                        UserSkill userSkill=new UserSkill();
                        userSkill.setWeakSkills(listWeak);
                        userSkill.setStrongSkills(listStrong);
                        userSkill.update(object.get(0).getObjectId(),new UpdateListener() {
                            @Override
                            public void done(BmobException e) {
                                if(e==null){
                                    listener.succeed();
                                }else{
                                    listener.failed();
                                }
                            }
                        });
                    }else if(object.size()==0){                 //不存在这条记录，则创建
                        UserSkill userSkill=new UserSkill();
                        userSkill.setUser(user);
                        userSkill.setWeakSkills(listWeak);
                        userSkill.setStrongSkills(listStrong);
                        userSkill.save(new SaveListener<String>() {
                            @Override
                            public void done(String s, BmobException e) {
                                if(e==null){
                                    listener.succeed();
                                }else{
                                    listener.failed();
                                }
                            }
                        });
                    }else{
                        listener.failed();
                    }
                }else {
                    listener.failed();
                }
            }
        });

    }


    public interface achieveSkillsListener{
        void succeed(String[] skills);
        void failed();
    }
    public interface achieveUserSkillsListener{
        void succeed(String[] weakSkills,String[] strongSkills);
        void failed();
    }
    public interface updateUserSkillListener{
        void succeed();
        void failed();
    }
    public interface achieveAllUserSkillsListerner{
        void succeed(List<UserSkill> list);
        void failed();
    }
}
